import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, setToken, removeToken } from '@/utils/setToken.js'
import store from '@/store'
import { getuserinfo } from '@/utils/api.js'
// 前置首位验证token
router.beforeEach((to, from, next) => {
  NProgress.start()
  // if(to.path ==='/login') return next()
  // // 获取token
  const tokenStr = getToken('token')
  // 登录判断
  if (tokenStr) {
    if (to.path == '/login') {
      console.log(11);
      next({ path: '/' })
    } else {
      // const hasGetUserInfo =  getToken('userinfo')
      const hasGetUserInfo = store.state.qi_user.info.name
      if (hasGetUserInfo) {
        next()
      } else {
        getuserinfo().then(resinfo => {
          if (resinfo == 200) {
            let user = {
              name: resinfo.data.name,
              avatar: resinfo.data.avatar,
              buttons: resinfo.data.buttons,
              routes: resinfo.data.routes
            }
            // setToken('userinfo',JSON.stringify(user))
            store.commit('qi_user/SETINFO', user)
            next()

          } else {
            removeToken('userinfo')
            removeToken('token')
            // 跳转到登录页
            router.push({ path: '/login', query: { redirect: to.path } })
          }
        })

      }
    }
  } else {
    // 用户未登录判断
    if (to.path == '/login') {
      console.log(21);
      next()
    } else {
      console.log(33);
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
  // if(!tokenStr && to.path !== '/login'){
  //   next('/login')
  // }else if(tokenStr && to.path === '/login') {
  //   next(from)
  // }else{
  //   next()
  // }  
})
router.afterEach((to, from) => {
  NProgress.done()
})